package model;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import annotations.Colonne;
import annotations.Id;
import annotations.Table;

public class Model {

    private Map<String, Object>	values	= new HashMap<String, Object>();
    private Map<String, String>	types	= new HashMap<String, String>();
	public String		TableName		=	null;
 
	public	Model(Object object)
	{
		boolean			tflag = false;
		boolean			iflag	=	false;
		Field[]				fields;
		Annotation[]	annotations;

		try {
			/*
			 * Recuperation de nom de la table
			 */
			annotations = object.getClass().getAnnotations();
			for (Integer i = 0; i < annotations.length; i++)
				if (annotations[i] instanceof	Table){
					Table mytab = (Table)	annotations[i];
					this.TableName = mytab.name();
					tflag = true;
				}
			if (tflag == false)
				throw new Exception("Annotation @Table(name=\"?\") manquante");
			
			String	column;
			Object	obj;
			/*
			 * Recuperaton des attributs de l' objet
			 */
			fields	=	object.getClass().getDeclaredFields();
			for (Integer j = 0; j < fields.length; j++)
			{
				annotations =	fields[j].getAnnotations();
				for (Integer i = 0; i < annotations.length; i++)
					if (annotations[i] instanceof	Id){
						iflag	=	true;
						column = fields[j].getName();
						fields[j].setAccessible(true);
						obj			=	fields[j].get(object);
						this.values.put(column, obj);
					}
					else if (annotations[i] instanceof Colonne){
						Colonne	mycol = (Colonne) annotations[i];
						column	=	mycol.name();
						fields[j].setAccessible(true);
						obj			=	fields[j].get(object);
						this.values.put(column, obj);
					}
			}
			if (iflag == false)
				throw new Exception("Annotation @Id manquante");
			
		}
		catch (Exception e) {	System.out.println(e.getMessage());	}
	}

	public Map<String, Object> getValues() {
		return values;
	}

	public void setValues(Map<String, Object> values) {
		this.values = values;
	}

	public Map<String, String> getTypes() {
		return types;
	}

	public void setTypes(Map<String, String> types) {
		this.types = types;
	}

	public String getTableName() {
		return TableName;
	}

	public void setTableName(String tableName) {
		TableName = tableName;
	}
	
}
